package com.panopset;

import java.io.File;
import java.util.HashMap;

/**
 * Object cross reference map.
 *
 * @author Karl Dinwiddie
 * @param <T>
 *            Object type.
 */
public final class CrossReference<T> {

    /**
     * File.
     */
    private File f;

    /**
     * Create a persistent cross reference. Type must be serializable.
     *
     * @param file
     *            File to store cross reference in.
     */
    public CrossReference(final File file) {
        f = file;
    }

    /**
     * Create a non-persistent cross reference object.
     */
    public CrossReference() {

    }

    /**
     * Map.
     */
    private HashMap<T, T> map;

    /**
     * @return map.
     */
    @SuppressWarnings("unchecked")
    private HashMap<T, T> getMap() {
        if (map == null) {
            if (f != null) {
                try {
                    map = (HashMap<T, T>) UtilIO.loadObject(HashMap.class,
                            f);
                } catch (final Exception ex) {
                    Util.log(ex);
                }
            }
            if (map == null) {
                map = new HashMap<T, T>();
            }
        }
        return map;
    }

    /**
     * Assign a cross reference pair.
     *
     * @param key
     *            Key.
     * @param match
     *            Match.
     */
    public void assign(final T key, final T match) {
        getMap().put(key, match);
        if (f != null) {
            UtilIO.saveObject(getMap(), f);
        }
    }

    /**
     * @param key
     *            Key to translate.
     * @return Translated key.
     */
    public T match(final T key) {
        T rtn = getMap().get(key);
        if (rtn == null) {
            return key;
        }
        return rtn;
    }

}
